<?php
namespace script;

use script\Db;

/**
 * 数据清洗类
 * @author sunhaoqiang(shqdev@163.com)
 * @time: 2019-08-25 16:38
*/

class Item
{
    protected $item = [];
    protected $data = [];
    protected $table;
    protected $db;
    public function __construct()
    {
        $option = [
            'host' 		=> '127.0.0.1',
            'user' 		=> 'root',
            'pass' 		=> 'root',
            'dbname' 	=> 'spider',
            'port' 		=> 3306,
            'charset' 	=> 'utf8'
        ];
        $this->db = Db::connect($option);

    }
    public function goCheck()
    {    
    }
    public function push(Array $data)
    {
        if (!empty($data)) {
            $data = $this->formatField($data);
            array_push($this->data, $data);
        }
    }
    public function mergeData(Array $data)
    {
        $data = array_map([$this, 'formatField'], $data);
        $data = array_filter($data);
        $this->data = array_merge($this->data, $data);
    }
    public function toDb()
    {   
        if (empty($this->table)) {
            return false;
        }
        if (empty($this->data)) {
            return false;
        }
        return $this->db->table($this->table)->addAll($this->data);   
    }
    /**
     * 格式化字段
     */
    public function formatField($data)
    {
        if (empty($data)) {
            return [];
        }
        
        foreach ($data as $key => $value) {
            if (array_key_exists($key, $this->item)) {
                if (is_string($data[$key])) {
                    $data[$key] = $this->escape($data[$key]);
                }elseif (is_array($data[$key])) {
                    $data[$key] = $this->escape(json_encode($data[$key]));
                }elseif (is_object($data[$key])){
                    $data[$key] = $this->escape(json_encode($data[$key]));
                }
            }else {
                unset($data[$key]);
            }
        }
        return $data;
    }
    /**
     * 转换双引号和单引号
     */

    public function escape($str)
    {
        return htmlspecialchars($str, ENT_QUOTES);
    }

    public function getPublicVars()
    {
        // $vars = get_object_vars($this);
        $class = new \ReflectionClass($this);
        $class_name = $class->getName();
        $vars = $class->getProperties(\ReflectionProperty::IS_PUBLIC);
        $item = array_map(function ($data) use ($class_name)
                    {
                        if ($class_name == ($data->class)) {
                            return $data->name;
                        }
                    }, $vars);
        /**
         * array_filter函数的功能是利用回调函数来对数组进行过滤，
         * 一直都以为用回调函数才能处理，却没有发现手册下面还有一句，
         * 如果没有回调函数，那么默认就是删除数组中值为false的项目。
         */
        return array_filter($item);
    }
}

